<template>
  <z-screen-container :loading="loading">
    <Header />
    <div
      class="map-wrap"
      :class="{ 'comparison-mode': visibleTowScren }"
    >
      <!-- 图层管理 -->
      <div
        class="sidebar"
        :class="{ istwo: visibleTowScren }"
        v-show="visibleLayerManager"
      >
        <div class="layer-title">
          <div class="title-label">图层管理</div>
          <div
            class="title-close"
            @click="closeLayerManager()"
          >
            <img
              style="width: 20px; height: 20px; margin-top: 10px"
              src="@/assets/imgs/close.png"
              alt=""
              class="item-img"
            />
          </div>
        </div>
        <div class="layer-content">
          <div
            class="layer-item"
            v-for="(layer, index) in layers"
            :key="index"
            @click="zoomToLayer(layer)"
          >
            <div class="layer-check">
              <el-checkbox
                :disabled="layer.get('type') === 'base'"
                :model-value="layer.getVisible()"
                @change="(val) => setLayerVisible(val, layer)"
              />
            </div>
            <div
              class="layer-name"
              :class="{ 'base-layer': layer.get('type') === 'base' }"
            >
              {{ layer.get('name') }}
            </div>
          </div>
        </div>
      </div>
      <div class="map-container">
        <div
          class="map"
          id="map"
        ></div>
        <div
          class="map2"
          id="map2"
          v-show="visibleTowScren"
        ></div>
      </div>
      <!-- 卷帘分析 -->

      <div
        id="slider"
        ref="sliderRef"
        class="slider"
        v-show="visiblesplit"
      >
        <div class="slider-header">
          <div class="title-label">卷帘分析</div>
          <div
            class="title-close"
            @click="closeSwipeAnalysis"
          >
            <img
              style="width: 20px; height: 20px; margin-top: 10px"
              src="@/assets/imgs/close.png"
              class="item-img"
              alt=""
            />
          </div>
        </div>
        <div class="selectLayer">
          <el-select
            v-model="swipeLayer"
            popper-class="custom-select-dropdown"
            @change="swipeChangehandler"
          >
            <el-option
              v-for="(item, index) in sublayers"
              :key="index"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </div>
        <div class="slider-track">
          <div
            class="slider-handle"
            :style="{ left: `${swipe * 100}%` }"
          ></div>
        </div>
      </div>
      <!-- 缓冲分析 -->
      <div
        class="draw-tools"
        v-show="visibleBuffer"
      >
        <div class="draw-title">
          <div class="title-label">缓冲分析</div>
          <div
            class="title-close"
            @click="closeBuffer()"
          >
            <img
              style="width: 20px; height: 20px; margin-top: 10px"
              src="@/assets/imgs/close.png"
              alt=""
              class="item-img"
            />
          </div>
        </div>
        <div class="draw-type">
          <div class="analysis-label">绘制方式：</div>
          <div class="buttons">
            <el-button
              v-for="tool in drawTools"
              :key="tool.type"
              :type="currentTool === tool.type ? 'warning' : 'primary'"
              @click="handleDrawClick(tool.type)"
              size="small"
            >
              <el-tooltip
                class="box-item"
                effect="dark"
                :content="tool.label"
                placement="top"
              >
                <img
                  :src="getAssetsImageUrl(tool.img)"
                  alt=""
                  class="item-img"
                />
              </el-tooltip>
            </el-button>

            <el-button
              type="danger"
              size="small"
              style="width: 80px"
              @click="handleClear"
            >
              <img
                src="@/assets/imgs/clear.png"
                style="width: 20px; height: 20px; margin: 8px 6px"
                alt=""
                class="item-img"
              />清空
            </el-button>
          </div>
        </div>
        <div class="draw-type">
          <div class="analysis-label">缓冲半径：</div>
          <el-input-number
            v-model="bufferRequest.radius"
          ></el-input-number>
        </div>
        <div
          class="draw-type"
          style="display: flex; justify-content: center"
        >
          <el-button
            type="primary"
            style="background-color: #0963c1; width: 160px; height: 50px"
            @click="handleBuffer"
            >分析</el-button
          >
        </div>
      </div>
      <!-- 邻近分析 -->
      <div
        class="near-analysis"
        v-show="visibleNear"
      >
        <div class="draw-title">
          <div class="title-label">邻近分析</div>
          <div
            class="title-close"
            @click="closeNear()"
          >
            <img
              style="width: 20px; height: 20px; margin-top: 10px"
              src="@/assets/imgs/close.png"
              alt=""
              class="item-img"
            />
          </div>
        </div>
        <div class="draw-type">
          <div class="analysis-label">绘制方式：</div>
          <div class="buttons">
            <el-button
              type="primary"
              @click="handleDrawClick('Point', true)"
              size="small"
            >
              <el-tooltip
                class="box-item"
                effect="dark"
                content="绘制点"
                placement="top"
              >
                <img
                  style="width: 20px; height: 20px; margin: 10px"
                  alt=""
                  src="@/assets/imgs/draw-point.png"
                />
              </el-tooltip>
            </el-button>
            <el-button
              type="danger"
              size="small"
              style="width: 80px"
              @click="handleClear"
            >
              <img
                src="@/assets/imgs/clear.png"
                style="width: 20px; height: 20px; margin: 8px 6px"
                alt=""
                class="item-img"
              />清空
            </el-button>
          </div>
        </div>

        <div
          class="draw-type"
          style="display: flex; justify-content: center"
        >
          <el-button
            type="primary"
            style="background-color: #0963c1; width: 160px; height: 50px"
            @click="handleNear"
            >分析</el-button
          >
        </div>
        <div class="draw-result">
          <div
            class="result-item"
            v-for="(item, index) in nearResults"
            :key="index"
            @dblclick="gotoItem(item)"
          >
            <div class="result-title">{{ getResultInfo(item) }}</div>
          </div>
        </div>
      </div>
      <!-- 工具栏 -->
      <div class="tools">
        <div
          v-for="(item, index) in toolMenus"
          :key="index"
          :class="{ active: item.active, 'tool-item': true }"
          @click="clickToolHandler(item.value)"
        >
          {{ item.label }}
        </div>
      </div>
      <div
        v-if="coordinates"
        class="coordinates-info"
      >
        <el-card>
          <template #header>
            <div class="card-header">
              <span>坐标信息</span>
              <el-button
                type="primary"
                size="small"
                @click="copyCoordinates"
              >
                复制坐标
              </el-button>
            </div>
          </template>
          <pre>{{ coordinates }}</pre>
        </el-card>
      </div>

      <!-- 添加弹出窗口 -->
      <el-dialog
        v-model="dialogVisible"
        title="要素详情"
        width="800px"
        destroy-on-close
      >
        <div class="feature-detail">
          <div class="image-container">
            <div class="image-wrapper">
              <el-image
                :src="getImageUrl(selectedFeature, '2022')"
                fit="cover"
                :preview-src-list="getImageUrl(selectedFeature, '2022')"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>图片加载失败</span>
                  </div>
                </template>
              </el-image>
              <div class="image-title">2022年影像</div>
            </div>
            <div class="image-wrapper">
              <el-image
                :src="getImageUrl(selectedFeature, '2025')"
                fit="cover"
                :preview-src-list="[getImageUrl(selectedFeature, '2025')]"
              >
                <template #error>
                  <div class="image-error">
                    <el-icon><Picture /></el-icon>
                    <span>图片加载失败</span>
                  </div>
                </template>
              </el-image>
              <div class="image-title">2025年影像</div>
            </div>
          </div>

          <el-table
            :data="getFeatureTableData"
            border
            style="margin: 20px 0"
          >
            <el-table-column
              prop="year"
              label="年份"
              width="180"
            />
            <el-table-column
              prop="area"
              label="面积(平方米)"
              width="180"
            />
            <el-table-column
              prop="status"
              label="状态"
            />
          </el-table>

          <div class="feature-description">
            <h4>描述信息：</h4>
            <p>{{ selectedFeature?.description || '暂无描述' }}</p>
          </div>
        </div>
      </el-dialog>

      <!-- 双屏对比控制面板 -->
      <div
        class="comparison-panel"
        v-show="visibleTowScren"
      >
        <div class="panel-header">
          <div class="title-label">双屏对比</div>
          <div
            class="title-close"
            @click="closeComparison"
          >
            <img
              style="width: 20px; height: 20px; margin-top: 10px"
              src="@/assets/imgs/close.png"
              alt=""
              class="item-img"
            />
          </div>
        </div>
        <div class="panel-content">
          <div class="layer-list">
            <div
              class="layer-item"
              v-for="(layer, index) in layers_tow"
              :key="index"
            >
              <div class="layer-check">
                <el-checkbox
                  :disabled="layer.get('type') === 'base'"
                  :model-value="layer.getVisible()"
                  @change="(val) => handleLayerVisibility(val, layer)"
                />
              </div>
              <div class="layer-name">{{ layer.get('name') }}</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </z-screen-container>
</template>
<script setup>
// 导入必要的组件和工具
import { GIS } from '@/utils/gis.js'
import { onMounted, reactive, ref, computed, nextTick, onBeforeUnmount } from 'vue'
import VectorLayer from 'ol/layer/Vector'
import { Location, Delete, Picture, Close } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import RemoteApi from '@/api/remoteData'
import DictApI from '@/api/dict'
import Header from './components/Header.vue'
import fullscreen from '@/utils/fullscreen.js'

// 基础状态变量
const loading = ref(false) // 加载状态
const currentTool = ref('') // 当前选中的绘制工具
const coordinates = ref(null) // 坐标信息
const visibleTowScren = ref(false) // 双屏显示状态
const visiblesplit = ref(false) // 卷帘分析显示状态
const visibleBuffer = ref(false) // 缓冲分析显示状态
const visibleNear = ref(false) // 邻近分析显示状态
const visibleLayerManager = ref(false) // 图层管理显示状态
const features = ref([]) // 要素数据
const layers = ref([]) // 图层列表
const layers_tow = ref([])
const sublayers = ref([]) // 子图层列表
const sliderRef = ref(null) // 卷帘滑块引用
const swipe = ref(0) // 卷帘位置
const currentLayer = ref(null) // 当前选中的图层
const nearResults = ref([]) // 邻近分析结果
const suspectedList = ref([]) // 疑似列表
const tempToLocationLayer = ref(null) // 临时定位图层

// 分析相关状态
const swipeLayer = ref('') // 卷帘图层
const activeTypes = ref(['1', '2', '3']) // 默认展开的类型
const bufferRequest = ref({ wkt: '', radius: 10 }) // 缓冲分析请求参数
const nearRequest = ref({ wkt: '', limit: 10 }) // 邻近分析请求参数
const handler_status = ref(null) // 处理器状态
const dict_questiontypes = ref([]) // 问题类型字典

// 类型名称映射
const typeNames = {
  kf: '疑似乱砍伐',
  dj: '疑似乱搭建',
  3: '类型三',
}

// 工具栏菜单配置
const toolMenus = ref([
  { label: '图层管理', value: 'layerManage', active: false },
  { label: '缓冲分析', value: 'buffer', active: false },
  { label: '卷帘分析', value: 'analysis', active: false },
  { label: '邻近分析', value: 'near', active: false },
  { label: '双屏对比', value: 'comparison', active: false },
])

/**
 * 获取类型名称
 * @param {string} type - 类型代码
 * @returns {string} 类型名称
 */
const getTypeName = (type) => {
  return typeNames[type] || `类型${type}`
}

/**
 * 按类型分组的要素计算属性
 * @returns {Array} 分组后的要素数组
 */
const groupedFeatures = computed(() => {
  const groups = {}
  features.value.forEach((item) => {
    if (!groups[item.ty]) {
      groups[item.ty] = {
        type: item.ty,
        items: [],
      }
    }
    groups[item.ty].items.push(item)
  })
  return Object.values(groups).sort((a, b) => a.type - b.type)
})

const getAssetsImageUrl = (name) => {
  // `import.meta.url` 是 Vite 提供的一个变量，它指向当前文件的 URL。
  // `new URL(...)` 会基于这个 URL 来解析相对路径，
  // 确保无论在开发环境还是生产环境，路径都是正确的。
  return new URL(`../../assets/imgs/${name}`, import.meta.url).href
}

// 绘制工具配置
const drawTools = [
  { type: 'Point', label: '绘制点', img: 'draw-point.png' },
  { type: 'LineString', label: '绘制线', img: 'draw-line.png' },
  { type: 'Polygon', label: '绘制面', img: 'draw-reg.png' },
  // { type: 'Circle', label: '绘制圆', icon: 'CircleCheck' },
]

// 天地图密钥配置
const TDT_KEY = import.meta.env.VITE_TIANDITU_KEY

// 初始化地图实例
const gis = reactive(
  new GIS({
    apiKey: TDT_KEY || 'f4d0553a23372a2f48c74851c7e46f4d',
    container: 'map',
  }),
)
const gis2 = reactive(
  new GIS({
    apiKey: TDT_KEY || 'f4d0553a23372a2f48c74851c7e46f4d',
    container: 'map2',
  }),
)

// 双屏对比相关状态
const leftMapLayer = ref('')
const rightMapLayer = ref('')

const layerStates = ref({}) // 添加图层状态管理

// 更新图层状态
const updateLayerStates = () => {
  const newStates = {}
  layers.value.forEach((layer) => {
    newStates[layer.get('name')] = {
      visible: layer.getVisible(),
      type: layer.get('type'),
      name: layer.get('name'),
    }
  })
  layerStates.value = newStates
}

/**
 * 设置图层可见性
 * @param {boolean} value - 可见性状态
 * @param {Object} layer - 图层对象
 */
const setLayerVisible = (value, layer) => {
  if (layer.get('type') === 'base') return // 不允许修改底图可见性
  layer.setVisible(value)
  updateLayerStates() // 更新状态

  // 如果在双屏模式下，同步到第二个地图
  // if (visibleTowScren.value) {
  //   const layers1 = gis.getlayertype()
  //   const layers2 = gis2.getlayertype()
  //   const index = layers1.indexOf(layer)
  //   if (index !== -1 && index < layers2.length) {
  //     const layer2 = layers2[index]
  //     if (layer2 instanceof VectorLayer) {
  //       layer2.setVisible(value)
  //     }
  //   }
  // }
}

/**
 * 缩放到指定图层
 * @param {Object} layer - 目标图层
 */
const zoomToLayer = (layer) => {
  gis.zoomToLayer(layer)
}

/**
 * 处理绘制工具点击事件
 * @param {string} type - 绘制类型
 * @param {boolean} isbuffer - 是否为缓冲分析
 */
const handleDrawClick = (type, isbuffer = false) => {
  if (currentTool.value === type) {
    gis.stopDraw()
    currentTool.value = ''
  } else {
    if (isbuffer) {
      gis.startDraw(type, nearDrawResult)
    } else {
      gis.startDraw(type, drawResult)
    }
    currentTool.value = type
  }
}

/**
 * 邻近分析绘制结果处理
 * @param {string} wkt - WKT格式的几何数据
 */
const nearDrawResult = (wkt) => {
  nearRequest.value.wkt = wkt
}

/**
 * 绘制结果处理
 * @param {string} wkt - WKT格式的几何数据
 */
const drawResult = (wkt) => {
  bufferRequest.value.wkt = wkt
  console.log(wkt)
}

/**
 * 关闭缓冲分析
 */
const closeBuffer = () => {
  gis.clearDraw()
  gis.stopDraw()
  visibleBuffer.value = false
  toolMenus.value.forEach((item) => {
    if (item.value === 'buffer') {
      item.active = false
    }
  })
}

/**
 * 处理缓冲分析
 */
const handleBuffer = () => {
  if (!bufferRequest.value.wkt || bufferRequest.value.wkt == '') {
    ElMessage.error('请绘制缓冲要素')
    return
  }
  if (!bufferRequest.value.radius) {
    ElMessage.error('请填写缓冲范围')
    return
  }
  RemoteApi.bufferAnalysis(bufferRequest.value).then((res) => {
    gis.renderBuffer(res.message)
    bufferRequest.value = { wkt: '', radius: 10 }
  })
  // Todo
}
const handleNear = () => {
  if (!nearRequest.value.wkt || nearRequest.value.wkt == '') {
    ElMessage.error('请绘制点要素')
    return
  }
  RemoteApi.nearestAnalysis(nearRequest.value.wkt, nearRequest.value.limit).then((res) => {
    console.log(res)
    nearResults.value = res.data
    gis.stopDraw()
  })
}
const handleClear = () => {
  gis.clearDraw()
  coordinates.value = null
  currentTool.value = ''
}
const closeNear = () => {
  gis.clearDraw()
  gis.stopDraw()
  visibleNear.value = false
  toolMenus.value.forEach((item) => {
    if (item.value === 'near') {
      item.active = false
    }
  })
}
const gotoItem = (item) => {
  console.log('1121', item)
  if (!tempToLocationLayer.value) {
    tempToLocationLayer.value = gis.addVectorLayer('临时图层', 'temp')
  } else {
    gis.clearLayer(tempToLocationLayer.value)
  }
  if (item.geom) {
    gis.renderBuffer(item.geom, tempToLocationLayer.value, {
      strokeColor: 'white',
      strokeWidth: 3,
      fillColor: 'rgba(255, 0, 0, 0.5)',
    })
  }
  gis.zoomToWkt(item.geom)
}

const handleLocate = (item) => {
  console.log(item)
  // gis.locateFeature(item.id);
}

const closeLayerManager = () => {
  visibleLayerManager.value = false
  toolMenus.value.forEach((item) => {
    if (item.value === 'layerManage') {
      item.active = false
    }
  })
}
const clickToolHandler = (value) => {
  toolMenus.value.forEach((item) => {
    item.active = false
  })
  closeAll()
  switch (value) {
    case 'comparison':
      if (!visibleTowScren.value) {
        visibleTowScren.value = true
        visibleLayerManager.value = true

        layers.value = gis.getlayertype()
        nextTick(() => {
          initSecondMap()
        })
      } else {
        closeComparison()
      }
      break
    case 'layerManage':
      if (!visibleLayerManager.value) {
        // 获取所有图层并初始化状态
        layers.value = gis.getlayertype()
        // 确保图层列表按顺序排列：底图在前，其他图层在后
        layers.value.sort((a, b) => {
          if (a.get('type') === 'base') return -1
          if (b.get('type') === 'base') return 1
          return 0
        })
        updateLayerStates() // 初始化图层状态
        visibleLayerManager.value = true
      } else {
        closeLayerManager()
      }
      break
    case 'buffer':
      if (!visibleBuffer.value) {
        visibleBuffer.value = true
        currentTool.value = true
      } else {
        closeBuffer()
      }
      break
    case 'analysis':
      if (!visiblesplit.value) {
        initSwipeLayer()
        visiblesplit.value = true
        handler_status.value = handleSlider()
      } else {
        closeSwipeAnalysis()
      }
      break

    case 'near':
      if (!visibleNear.value) {
        nearResults.value = []
        nearRequest.value.wkt = ''
        visibleNear.value = true
      } else {
        closeNear()
      }
      break
  }
}
const closeAll = () => {
  closeLayerManager()
  closeNear()
  closeSwipeAnalysis()
  closeBuffer()
  closeComparison()
}
const initSwipeLayer = () => {
  layers.value = gis.getlayertype()

  sublayers.value = layers.value
    .filter((layer) => layer.get('type') !== 'base')
    .map((layer) => ({
      name: layer.get('name'),
      value: layer.get('name'),
    }))

  if (sublayers.value.length > 0) {
    swipeLayer.value = sublayers.value[0].value
    swipeChangehandler(swipeLayer.value)
  }
}
const swipeChangehandler = (val) => {
  const selectedLayer = layers.value.find((layer) => layer.get('name') === val)

  if (!selectedLayer) return

  if (currentLayer.value) {
    gis.clearEvent(currentLayer.value)
  }

  currentLayer.value = selectedLayer
  gis.initswipelayer(currentLayer.value)
}
const copyCoordinates = () => {
  if (coordinates.value) {
    navigator.clipboard
      .writeText(JSON.stringify(coordinates.value, null, 2))
      .then(() => {
        ElMessage.success('坐标已复制到剪贴板')
      })
      .catch(() => {
        ElMessage.error('复制失败')
      })
  }
}

// 加载要素数据
const loadFeatures = async () => {
  try {
    const response = await fetch('/data/data.json') // public/data/points.json
    if (!response.ok) throw new Error('Failed to load JSON')
    const points = await response.json()
    // const response = await axios.get('/data/data.json');
    features.value = points

    gis.renderFeatures(points, clickFeatureCallback)
  } catch (error) {
    ElMessage.error('加载要素数据失败')
    console.error('加载要素数据失败:', error)
  }
}

// 添加新的响应式数据
const dialogVisible = ref(false)
const selectedFeature = ref(null)

// 获取图片URL的方法
const getImageUrl = (feature, year) => {
  if (!feature) return ''
  console.log(feature)
  return `/data/${feature.ty}/${feature.typeid}/${feature.ty}-${feature.typeid}-${year}.png`
}
const getResultInfo = (result) => {
  console.log('11111', result, dict_questiontypes.value)
  const info = dict_questiontypes.value.find((t) => t.dictionaryCode == result.dataType)
  if (info) {
    return info.dictionaryName + ': ' + result.analysisText
  } else {
    return ''
  }
}

// 获取表格数据的计算属性
const getFeatureTableData = computed(() => {
  if (!selectedFeature.value) return []
  return [
    {
      year: '2022',
      area: selectedFeature.value.area2022 || '-',
      status: selectedFeature.value.status2022 || '-',
    },
    {
      year: '2023',
      area: selectedFeature.value.area2023 || '-',
      status: selectedFeature.value.status2023 || '-',
    },
  ]
})

// 修改点击要素回调函数
const clickFeatureCallback = (data) => {
  console.log(data)
  selectedFeature.value = data
  dialogVisible.value = true
}
const loadData = () => {
  gis.loadGeoJSON('/baoji.geojson', {
    layerName: '宝鸡',
    layerType: 'relate',
    textfiled: 'name',
    style: {
      type: 'polygon',
      fillcolor: 'rgba(236, 156, 77, 0.7)',
      strokeColor: 'rgba(236, 156, 77, 1)',
      strokeWidth: 2,
      textcolor: '#ffffff',
    },
  })
  gis.loadGeoJSON('/protected_area.geojson', {
    layerName: '自然保护区域',
    layerType: 'relate',
    textfiled: 'code',
    style: {
      type: 'polygon',
      fillcolor: 'rgba(80,138,248,0.8)',
      strokeColor: 'rgba(107,243,230,1.00)',
      strokeWidth: 2,
      textcolor: '#ffffff',
    },
  })
  gis.loadGeoJSON('/river_area.geojson', {
    layerName: '河流面',
    layerType: 'relate',
    textfiled: '',
    style: {
      type: 'polygon',
      fillcolor: '#28ade1cd',
      strokeColor: '#28ade1cd',
      strokeWidth: 0,
      textcolor: '#ffffff',
    },
  })
  gis.loadGeoJSON('/river_line.geojson', {
    layerName: '河流线',
    layerType: 'relate',
    textfiled: '',
    style: {
      type: 'line',
      fillcolor: '#28ade1cd',
      strokeColor: '#28ade1cd',
      strokeWidth: 0,
      textcolor: '#ffffff',
    },
  })

  gis.loadGeoJSON('/forest_point.geojson', {
    layerName: '森林公园',
    layerType: 'relate',
    textfiled: 'name',
    style: {
      type: 'icon',
      img: '/foreast.png',
      textcolor: '#00ff00',
    },
  })
  gis.loadGeoJSON('/protected_point.geojson', {
    layerName: '自然保护区',
    layerType: 'relate',
    textfiled: 'name',
    minZoom: 8,
    style: {
      type: 'icon',
      img: '/area.png',
      textcolor: '#00ff00',
    },
  })
}

onMounted(async () => {
  DictApI.getDictItemsByCode('questiontypes').then((res) => {
    dict_questiontypes.value = res.data
    console.log(dict_questiontypes.value)
  })
  gis.initMap('image')
  loadData()

  const year = `${new Date().getFullYear()}-01-01`
  RemoteApi.getSuspectedList({ status: 1, year }).then((res) => {
    console.log('abaaba', res)
    suspectedList.value = res.data
    const layer = gis.addVectorLayer('线索图层', 'important')
    res.data.forEach((d) => {
      if (d.geom) {
        const style = {
          strokeColor: '#fed207',
          strokeWidth: 2,
          fillColor: 'rgba(255, 0, 0, 0.5)',
        }
        gis.renderBuffer(d.geom, layer, style)
      }
    })
  })

  // 监听绘制完成事件
  gis.map.on('drawend', (event) => {
    const feature = event.feature
    const geometry = feature.getGeometry()
    const type = geometry.getType()

    let coords
    switch (type) {
      case 'Point':
        coords = geometry.getCoordinates()
        coordinates.value = {
          type: '点',
          coordinates: coords,
        }
        break
      case 'LineString':
        coords = geometry.getCoordinates()
        coordinates.value = {
          type: '线',
          coordinates: coords,
          length: Math.round(geometry.getLength()) + ' 米',
        }
        break
      case 'Polygon':
        coords = geometry.getCoordinates()
        coordinates.value = {
          type: '面',
          coordinates: coords[0], // 外环坐标
          area: Math.round(geometry.getArea()) + ' 平方米',
        }
        break
      case 'Circle':
        const center = geometry.getCenter()
        const radius = geometry.getRadius()
        coordinates.value = {
          type: '圆',
          center: center,
          radius: Math.round(radius) + ' 米',
          area: Math.round(Math.PI * radius * radius) + ' 平方米',
        }
        break
    }
  })

  // 监听图层变化
  gis.map.getLayers().on('change', () => {
    if (visibleLayerManager.value) {
      updateLayerStates()
    }
  })
  if (fullscreen.isSupported()) {
    if (fullscreen.isActive()) {
      await fullscreen.exit()
    }
    await fullscreen.request()
  }
})

//
const handleSlider = () => {
  const slider = sliderRef.value
  if (!slider) return

  const move = (e) => {
    const rect = slider.getBoundingClientRect()
    const position = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width))
    swipe.value = position
    gis.updateSwipePosition(position)
  }

  const up = () => {
    window.removeEventListener('mousemove', move)
    window.removeEventListener('mouseup', up)
  }

  const down = (e) => {
    window.addEventListener('mousemove', move)
    window.addEventListener('mouseup', up)
    move(e)
  }

  slider.addEventListener('mousedown', down)

  return () => {
    slider.removeEventListener('mousedown', down)
  }
}

const closeSwipeAnalysis = () => {
  visiblesplit.value = false
  if (handler_status.value) {
    handler_status.value()
  }
  if (currentLayer.value) {
    gis.clearEvent(currentLayer.value)
    currentLayer.value = null
  }
  swipe.value = 0.5
  swipeLayer.value = ''
  toolMenus.value.forEach((item) => {
    if (item.value === 'analysis') {
      item.active = false
    }
  })
}

/**
 * 初始化第二个地图
 */
const initSecondMap = () => {
  gis2.initMap('image')
  // 复制第一个地图的所有图层到第二个地图
  const layers = gis.getlayertype()
  layers.forEach((layer) => {
    const layerName = layer.get('name')
    const layerType = layer.get('type')

    // 只处理矢量图层
    if (layer instanceof VectorLayer) {
      const source = layer.getSource()
      const style = layer.getStyle()
      const properties = layer.getProperties()

      // 创建新的矢量图层
      const newLayer = new VectorLayer({
        source: source,
        style: style,
        properties: properties,
      })

      gis2.map.addLayer(newLayer)
    }
  })

  // 同步地图视图和图层状态
  syncMaps()
  syncLayerVisibility()
}

// 添加事件监听器引用
const viewChangeListeners = ref({
  center: null,
  resolution: null,
})

/**
 * 同步两个地图的操作
 */
const syncMaps = () => {
  // 同步视图
  // const syncView = () => {
  //   const center = gis.map.getView().getCenter()
  //   const zoom = gis.map.getView().getZoom()
  //   gis2.map.getView().setCenter(center)
  //   gis2.map.getView().setZoom(zoom)
  // }

  // 只监听中心点变化，移除分辨率监听
  // viewChangeListeners.value.center = syncView
  // gis.map.getView().on('change:center', viewChangeListeners.value.center)
  let time1, time2
  gis.map.getView().on('change:center', () => {
    clearTimeout(time1)
    time1 = setTimeout(() => {
      const center = gis.map.getView().getCenter()
      const zoom = gis.map.getView().getZoom()
      gis2.map.getView().setCenter(center)
      gis2.map.getView().setZoom(zoom)
    }, 50)
  })
  // 监听第二个地图的视图变化
  gis2.map.getView().on('change:center', () => {
    clearTimeout(time2)
    time2 = setTimeout(() => {
      const center = gis2.map.getView().getCenter()
      const zoom = gis2.map.getView().getZoom()
      gis.map.getView().setCenter(center)
      gis.map.getView().setZoom(zoom)
    }, 50)
  })
}

/**
 * 同步图层可见性
 */
const syncLayerVisibility = () => {
  const layers1 = gis.getlayertype()
  const layers2 = gis2.getlayertype()

  layers1.forEach((layer1, index) => {
    if (index < layers2.length) {
      const layer2 = layers2[index]
      // 只同步矢量图层的可见性
      if (layer1 instanceof VectorLayer && layer2 instanceof VectorLayer) {
        layer2.setVisible(layer1.getVisible())
      }
    }
  })
  console.log("aaaac")
  layers.value=layers1
  layers_tow.value = layers2

}

/**
 * 处理图层可见性变化
 */
const handleLayerVisibility = (visible, layer) => {
  // 只处理矢量图层
  if (layer instanceof VectorLayer) {
    // layer.setVisible(visible)
    // 同步到第二个地图
    // const layers1 = gis.getlayertype()
    const layers2 = gis2.getlayertype()
    const index = layers2.indexOf(layer)
    if (index !== -1 && index < layers2.length) {
      const layer2 = layers2[index]
      if (layer2 instanceof VectorLayer) {
        layer2.setVisible(visible)
      }
    }
  }
}

/**
 * 关闭双屏对比
 */
const closeComparison = () => {
  // 移除视图同步事件监听
  if (viewChangeListeners.value.center) {
    gis.map.getView().un('change:center', viewChangeListeners.value.center)
    viewChangeListeners.value.center = null
  }
  toolMenus.value.forEach((item) => {
    if (item.value === 'comparison') {
      item.active = false
    }
  })

  // 清除所有图层
  // const layers2 = gis2.getlayertype()
  // layers2.forEach(layer => {
  //   if (layer instanceof VectorLayer) {
  //     layer.getSource().clear()
  //   }
  //   gis2.map.removeLayer(layer)
  // })

  // 销毁第二个地图实例
  gis2.destroy()

  // 重置状态
  visibleTowScren.value = false
  visibleLayerManager.value = false
  leftMapLayer.value = ''
  rightMapLayer.value = ''
}
</script>
<style lang="scss">
/* 自定义下拉框样式 */
.custom-select-dropdown {
  background-color: #1a3a6e !important;
  .el-select-dropdown__item {
    color: white;
  }
  /* 选中项样式 */
  .el-select-dropdown__item.is-selected {
    background-color: #37527d !important;
    color: #409eff !important;
  }
  /* 悬停项样式 */
  .el-select-dropdown__item:hover {
    background-color: #37527d !important;
    color: white;
  }
}
.custom-select-dropdown.el-select__popper.el-popper {
  background: #1a3a6e !important;
}
.custom-select-dropdown.el-popper.is-light,
.custom-select-dropdown.el-popper.is-light > .el-popper__arrow:before {
  background: #1a3a6e !important;
  border-color: #6dadff !important;
}
.custom-select-dropdown .el-select-dropdown__item.is-hovering {
  background: #37527d !important;
}
</style>
<style scoped lang="scss">
.map-wrap {
  width: 100%;
  height: 100%;
  position: absolute;
  :deep(.ol-zoom) {
    top: auto;
    bottom: 15px;
    left: 15px;
  }

  &.comparison-mode {
    .map,
    .map2 {
      width: 45%;
      height: 100%;
    }
  }

  .sidebar {
    position: absolute;
    right: 0;
    bottom: 0;
    top: 0;
    background-color: #1a3a6e;
    padding: 22px;
    width: 260px;
    border-radius: 8px;
    z-index: 1;
    opacity: 0.9;
    .layer-title {
      height: 40px;
      line-height: 40px;
      margin-bottom: 15px;
      fond-size: 20px;

      color: #ffffff;
      display: flex;
      text-align: center;

      .title-close {
        width: 40px;
        height: 40px;
        line-height: 40px;
      }
      .title-label {
        width: calc(100% - 40px);
        text-align: left;
      }

      .feature-item {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 8px 16px;

        border-bottom: 1px solid #f0f0f0;

        &:last-child {
          border-bottom: none;
        }

        span {
          flex: 1;
          margin-right: 8px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
    .layer-content {
      width: 100%;

      color: #fff;
      .layer-item {
        width: 100%;
        display: flex;
        justify-content: left;
        height: 50px;
        font-size: 16px;

        cursor: pointer;
        transition: background-color 0.3s;
        background-color: #001542;
        border-bottom: 1px solid #65a1ed;

        &:hover {
          background-color: #006ff2;
        }

        .layer-check {
          margin-top: 10px;

          height: 27px;
          width: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .layer-name {
          margin-top: 10px;
          flex: 1;
          line-height: 27px;
          padding-left: 8px;

          &.base-layer {
            color: #a0a0a0;
            font-style: italic;
          }
        }
      }
    }
  }
  .map-container {
    width: 100%;
    height: 100%;
    display: flex;
    position: absolute;
    left: 0;
    top: 0;
  }
  .map {
    flex: 1;
    height: 100%;
    background: #eee;
  }
  .tools {
    position: absolute;
    right: 20px;
    bottom: 80px;
    height: 35px;
    background-color: rgba(26, 58, 110, 0.75);
    border-radius: 4px;

    border: 1px solid #6dadff;
    user-select: none; /* 禁止选中 */
    -webkit-user-select: none; /* 兼容 WebKit 浏览器 */
    -moz-user-select: none; /* 兼容 Firefox */
    -ms-user-select: none; /* 兼容旧版 Edge */
    display: flex;
    .tool-item {
      width: 100px;
      height: 35px;
      text-align: center;
      border-right: 1px solid #ccc;
      line-height: 35px;
      color: #fff;
      cursor: pointer;

      // &:hover {
      //   background-color:  #00A1FF;
      // }
      &:last-child {
        border-right: none;
      }
    }
    .active {
      background-color: #00a1ff;
      opacity: 0.4;
    }
  }

  .draw-tools {
    position: absolute;
    top: 110px;
    right: 20px;
    padding: 10px;
    width: 268px;
    height: 361px;
    border-radius: 4px;
    background-color: #1a3a6e;
    opacity: 0.9;
    z-index: 1;
    .draw-title {
      height: 40px;
      line-height: 40px;
      font-size: 20px;
      color: #ffffff;
      display: flex;
      text-align: left;
      padding-left: 16px;

      .title-close {
        width: 40px;
        height: 40px;
        line-height: 40px;
      }
      .title-label {
        width: calc(100% - 40px);
        text-align: left;
      }
    }
    .draw-type {
      margin-top: 19px;
      width: 100%;
      margin: 20px auto;

      .analysis-label {
        width: 100px;
        height: 30px;
        color: #fff;
        font-size: 18px;
        text-align: left;
        line-height: 30px;
        margin: 10px 0;
      }
      .buttons {
        width: 100%;
        display: flex;
        justify-content: space-around;

        .el-button {
          width: 40px;
          height: 40px;

          .item-img {
            width: 24px;
            height: 24px;
            margin: 8px;
          }
        }
      }

      .el-input-number {
        width: calc(100% - 20px);
        height: 40px;
        margin: 10px;
        :deep(.el-input__wrapper) {
          background-color: #1a3a6e;
          box-shadow: none;
          padding: 0;
          border: 1px solid rgba(109, 173, 255, 0.8);
          color: #5bc9ff;
        }
      }
    }
  }
  .near-analysis {
    position: absolute;
    top: 110px;
    right: 20px;
    width: 200px;

    background-color: #1a3a6e;
    opacity: 0.9;
    padding: 10px;
    border-radius: 4px;
    z-index: 1000;
    overflow-x: hidden;
    overflow-y: auto;
    .draw-title {
      height: 40px;
      line-height: 40px;
      font-size: 20px;
      color: #ffffff;
      display: flex;
      text-align: left;
      padding-left: 16px;

      .title-close {
        width: 40px;
        height: 40px;
        line-height: 40px;
      }
      .title-label {
        width: calc(100% - 40px);
        text-align: left;
      }
    }
    .draw-type {
      margin-top: 19px;
      width: 100%;
      margin: 20px auto;

      .analysis-label {
        width: 100px;
        height: 30px;
        color: #fff;
        font-size: 18px;
        text-align: left;
        line-height: 30px;
        margin: 10px 0;
      }
      .buttons {
        width: 100%;
        display: flex;
        justify-content: space-around;
        .el-button {
          width: 40px;
          height: 40px;

          .item-img {
            width: 24px;
            height: 24px;
            margin: 8px;
          }
        }
      }
      .el-input-number {
        width: calc(100% - 20px);
        height: 40px;
        margin: 10px;
        :deep(.el-input__wrapper) {
          background-color: #1a3a6e;
          box-shadow: none;
          padding: 0;
          border: 1px solid rgba(109, 173, 255, 0.8);
          color: #5bc9ff;
        }
      }
    }
    .draw-result {
      width: calc(100% - 20px);
      margin: 10px;

      .result-item {
        width: 100%;
        color: #fff;
        height: 50px;
        white-space: nowrap; /* 不换行 */
        overflow: hidden; /* 隐藏超出的内容 */
        text-overflow: ellipsis; /* 用省略号表示被隐藏的部分 */
        max-width: 200px; /* 设置最大宽度以限制文本的显示长度 */
        cursor: pointer;
        line-height: 50px;
        border-bottom: 1px solid #ccc;
        line-height: 30px;
        &:last-child {
          border-bottom: none;
        }
        .result-title {
          line-height: 50px;
        }
      }
      .result-item:hover {
        background: #006ff2;
      }
    }
  }
  .slider {
    position: absolute;
    top: 120px;
    right: 20px;
    width: 300px;
    background: #092757;
    border-radius: 4px;
    z-index: 1000;

    .slider-header {
      height: 40px;
      line-height: 40px;
      background-color: #1a3a6e;
      color: #ffffff;
      display: flex;
      text-align: center;
      border-radius: 4px 4px 0 0;

      .title-close {
        width: 40px;
        height: 40px;
        line-height: 40px;
        cursor: pointer;
        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }
      }
      .title-label {
        width: calc(100% - 40px);
        text-align: left;
        padding-left: 15px;
      }
    }

    .slider-track {
      position: relative;
      height: 4px;
      background: #ddd;
      margin: 10px 15px 20px 15px;
      border-radius: 2px;
    }

    .slider-handle {
      position: absolute;
      top: 50%;
      width: 16px;
      height: 16px;
      background: #409eff;
      border-radius: 50%;
      transform: translate(-50%, -50%);
      // cursor: ew-resize;
      cursor: pointer;
      box-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    }
  }
  .coordinates-info {
    position: absolute;
    bottom: 20px;
    right: 20px;
    width: 300px;
    max-height: 400px;
    overflow-y: auto;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }

    pre {
      margin: 0;
      white-space: pre-wrap;
      word-wrap: break-word;
    }
  }

  .feature-detail {
    .image-container {
      display: flex;
      gap: 20px;
      margin-bottom: 20px;

      .image-wrapper {
        flex: 1;
        text-align: center;

        .el-image {
          width: 100%;
          height: 300px;
          border-radius: 4px;
          overflow: hidden;
        }

        .image-title {
          margin-top: 8px;
          font-size: 14px;
          color: #666;
        }

        .image-error {
          height: 100%;
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          color: #909399;
          background: #f5f7fa;

          .el-icon {
            font-size: 24px;
            margin-bottom: 8px;
          }
        }
      }
    }

    .feature-description {
      margin-top: 20px;

      h4 {
        margin: 0 0 10px 0;
        color: #333;
      }

      p {
        margin: 0;
        line-height: 1.6;
        color: #666;
      }
    }
  }

  .map2 {
    flex: 1;
    height: 100%;
    background: #eee;
  }

  .comparison-panel {
    position: absolute;
    top: 120px;
    right: 20px;
    width: 268px;

    background-color: #1a3a6e;
    opacity: 0.9;
    border-radius: 4px;
    z-index: 1000;
    color: #ffffff;

    .panel-header {
      height: 40px;
      line-height: 40px;

      color: #ffffff;
      display: flex;
      text-align: center;
      border-radius: 4px 4px 0 0;

      .title-close {
        width: 40px;
        height: 40px;
        line-height: 40px;
        cursor: pointer;
        &:hover {
          background-color: rgba(255, 255, 255, 0.1);
        }
      }
      .title-label {
        width: calc(100% - 40px);
        text-align: left;
        padding-left: 15px;
      }
    }

    .panel-content {
      padding: 15px;

      .layer-list {




        .layer-item {
          display: flex;
          align-items: center;
          // margin: 4px 0;
          border-bottom: 1px solid #eee;
          background-color: #001542;
          height: 50px;
          padding-left: 20px;

          &:last-child {
            border-bottom: none;
          }

          .layer-check {
            margin-right: 10px;
          }

          .layer-name {
            flex: 1;
            color: #ffffff;
          }
        }
      }
    }
  }
}
.selectLayer {
  padding: 20px 15px;
}
::-webkit-scrollbar-thumb {
  border-radius: 8px;
  border: 4px solid transparent;
  background-clip: content-box;
  background-color: #007ef2;
}
.item-img {
  cursor: pointer;
}
.istwo {
  position: absolute;
  right: none;
  bottom: auto !important;
  left: 20px;
  top: 120px!important;
}

// 隐藏input颜色
:deep(.el-select__wrapper) {
  background: #1a3a6e;
  border-radius: 2px;
  border: 1px solid #6dadff;
  opacity: 0.8;
  box-shadow: none;
  color: #fafeff;
}

:deep(.el-select__placeholder) {
  color: #fafeff;
}

:deep(.el-select-dropdown) {
  background-color: #1a3a6e !important;
  color: red;
}
/* 自定义输入框样式 */
:deep(.el-input__wrapper) {
  background: #1a3a6e;
  box-shadow: 0 0 0 1px var(--el-input-border-color, var(--el-border-color)) inset;
}
:deep(.el-input__inner) {
  color: white;
}
:deep(.input__placeholder) {
  color: white;
}
/* 自定义数字输入框样式 */
:deep(.el-input-number__decrease) {
  background: #1a3a6e;
  color: white;
  border-color: rgba(109, 173, 255, 0.8);
}
:deep(.el-input-number__increase) {
  background: #1a3a6e;
  color: white;
  border-color: rgba(109, 173, 255, 0.8);
}
</style>
